<template>
    <div class="internalTransactionRecordsPage">
        <div class="search-wrap d-flex a-center">

            <div class="search-item d-flex a-center m-l20">
                <label>债权方</label>
                <el-select class="m-l10" v-model="form.creditor" clearable>
                    <el-option v-for="(item,index) in companyList" :key="index" :label="item.companyName" :value="item.companyName"></el-option>
                </el-select>
            </div>
            <div class="search-item d-flex a-center m-l20">
                <label>债务方</label>
                <el-select class="m-l10" v-model="form.debtor" clearable>
                    <el-option v-for="(item,index) in companyList" :key="index" :label="item.companyName" :value="item.companyName"></el-option>
                </el-select>
            </div>
            <div class="search-buttons m-l50 d-flex a-center">
                <el-button
                        color="#fc702b"
                        style="color:#fff;"
                        @click.prevent="onQuery"
                >查询</el-button>
                <el-button
                        color="#f0f0f0"
                        style="color: #000000"
                        @click.prevent="onReset"
                >重置</el-button>
                <el-divider direction="vertical" />
                <el-button
                        @click="addHandle"
                        class="button_edit m-r10"
                >
                    <svg-icon icon-class="calculator" class="icon-export m-r5"></svg-icon>
                    计息计算
                </el-button>
                <el-button
                    :loading="initiateRepaymentLoading"
                    class="button_edit"
                    @click="initiateRepaymentHandle"
                >
                    发起还款
                </el-button>
                <el-button
                    :loading="initiateRepaymentLoading"
                    class="button_edit"
                    @click="viewDetails"
                >
                    查看明细
                </el-button>
                <el-button
                        class="button_edit"
                        @click="onExport"
                >
                    <svg-icon icon-class="project-detail-icon-derive" class="icon-export m-r5"></svg-icon>
                    一键导出
                </el-button>
            </div>
        </div>
        <public-table
                ref="publicTableRef"
                class="m-t20"
                index
                radio
                :indexWidth="'100'"
                :page="page"
                :tableData="tableData"
                :tableOption.sync="tableOption"
                @page-change="onPageChange"
                @handleSelectionChange="handleSelectionChange"
        >
            <template #repaymentAmountCount="scope">
                <span
                    style="cursor: pointer;color: #fc7037;"
                    @click="toDetails(scope.row,'1')"
                >{{scope.row.repaymentAmountCount}}</span>
            </template>
            <template #interestAmountCount="scope">
                <span
                    style="cursor: pointer;color: #fc7037;"
                    @click="toDetails(scope.row,'2')"
                >{{scope.row.interestAmountCount}}</span>
            </template>
        </public-table>
    </div>

  <!-- 导入excel   -->
    <public-dialog
            :title="'新增计息计算'"
            :width="'40%'"
            :confirmButtonTitle="'确认'"
            v-model:visible="visible"
            @onConfirm="onConfirm"
    >
        <div class="public-dialog-content d-flex flex-column">
          <el-form
              ref="formRef"
              :model="interestForm"
              :rules="interestRules"
              label-width="120">
              <div class="dialog-title-box d-flex a-center">
                  <span>银行信息</span>
              </div>
              <el-row>
                  <el-col :span="12">
                      <el-form-item label="债权方">
                          <el-input disabled :placeholder="selectedArr[0].creditor"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="债务方">
                          <el-input disabled :placeholder="selectedArr[0].debtor"></el-input>
                      </el-form-item>
                  </el-col>
              </el-row>
              <el-row>
                  <el-col :span="12">
                      <el-form-item label="借款时间">
                          <el-input disabled :placeholder="selectedArr[0].loanTime"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="借款总金额">
                          <el-input disabled :placeholder="selectedArr[0].loanAmount"></el-input>
                      </el-form-item>
                  </el-col>
              </el-row>
              <el-divider/>
              <div class="dialog-title-box d-flex a-center">
                  <span>计提计算器</span>
              </div>
              <el-row>
                  <el-col :span="12">
                      <el-form-item label="计提时间" prop="startTime">
                          <el-date-picker
                              v-model="interestForm.valueTime"
                              @change="onChange"
                              value-format="YYYY-MM-DD"
                              type="datetimerange"
                              range-separator="-"
                              start-placeholder="开始时间"
                              end-placeholder="结束时间"
                              size="large"
                          />
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="年天数">
                          <el-input disabled placeholder="365"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="4">
                      <el-button
                          class="button_view m-l10"
                          :loading="loading"
                          @click="onCount"
                      >计算</el-button>
                  </el-col>
              </el-row>
              <el-row>
                  <el-col :span="15">
                      <el-form-item label="计提计算结果（自动计算）" label-width="180">
                          <el-input disabled :placeholder="amountMoney"></el-input>
                      </el-form-item>
                  </el-col>
              </el-row>
          </el-form>
        </div>
    </public-dialog>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import {
    ElSelect,
    ElOption,
    ElDivider,
    ElMessage,
    ElForm,
    ElFormItem,
    ElRow,
    ElCol,
    ElDatePicker
} from "element-plus";
import PublicTable from "@/components/PublicTable.vue";
import PublicDialog from "@/components/PublicDialog.vue";

import {tableCommonFun} from "@/hooks/tableCommon";
import {bankManagementApi, companyApi} from "@/api/businessFinance";
import {useRouter} from "vue-router";

const interfaceConfig = reactive({
    fileName:'businessFinance',
    apiPath:'bankManagementApi.getInternalTransactionRecordList',
});
const exportConfig = reactive({
    fileName:'businessFinance',
    apiPath:'exportApi.getInternalTransactionRecordLeadingOut',
    tableName:'内部往来记录表'
});
const {
    form,
    page,
    tableOption,
    tableData,
    selectedArr,
    onQuery,
    onReset,
    onPageChange,
    getData,
    handleSelectionChange,
    onExport
}  = tableCommonFun(interfaceConfig,exportConfig);

form.value = {
    creditor:'',
    debtor:'',
    startTime:'',
    endTime:''
}

tableOption.value = [
  { label: "债权方 ", prop: "creditor", minWidth: 100 },
  { label: "债务方", prop: "debtor", minWidth: 100 },
  { label: "借款时间", prop: "loanTime", minWidth: 100 },
  { label: "借款金额", prop: "loanAmount", minWidth: 100 },
  { label: "利率", prop: "interestRate", minWidth: 80 },
  { label: "还款总金额", prop: "repaymentAmountCount", slot: true, minWidth: 100 },
  { label: "借款余额", prop: "loanBalance", minWidth: 100 },
  { label: "计提利息总金额", prop: "interestAmountCount", slot: true, minWidth: 130 },
  {
    label: "贷款余额", prop: "", formatter: (val, row) => {
      return row.loanAmount - row.repaymentAmountCount;
    }, minWidth: 80
  },
];


const companyList = ref([]);
/**
 * 查公司列表
 */
const getCompanyList = () => {
    companyApi.getList({}).then(res=>{
      companyList.value = res.data;
    });
}

const visible = ref(false);
const interestForm = reactive({
    startTime:"",
    endTime:"",
    valueTime:''
});
const interestRules  = reactive({
    startTime:[
        { required: true, message: '请输入计提时间', trigger: 'change' },
    ]
});

/**
 * 新增计息计算
 *
 */
const addHandle = () => {
    if(selectedArr.value.length===0){
        ElMessage.warning('请选择一条要操作的数据!');
        return;
    }
    visible.value = true;
}

/**
 * 计提计算
 *
 */
const interestCount = (param,callback) => {
    bankManagementApi.interestCount(param).then(res=>{
        if(res.code === '200'){
            if(callback)callback(res);
        }
    });
}

/**
 * 计提计算
 */
const formRef = ref(null);
const publicTableRef = ref(null);
const loading = ref(false);
const amountMoney = ref(0);
const onCount = () => {
    formRef.value.validate((valid, fields) => {
        if (valid) {
            loading.value = true;
            interestCount({
                loanBalance:selectedArr.value[0].loanBalance,
                interestRate:selectedArr.value[0].interestRate || 0,
                startTime:interestForm.startTime,
                endTime:interestForm.endTime,
                day:365
            },(res)=>{
                loading.value = false;
                amountMoney.value = res.data;
            });
        } else {
            console.log('error submit!', fields)
        }
    });
}

/**
 * 新增计息计算
 *
 */
const addInterest = (param,callback,err_callback) => {
    bankManagementApi.addInterest(param).then(res=>{
        if(res.code === '200'){
            if(callback)callback();
        }else{
            if(err_callback)err_callback();
        }
    });
}

/**
 * 新增计息计算确认
 *
 */
const onConfirm = () => {
    if(amountMoney.value===0){
        ElMessage.warning('计算计提计算结果不能为零,请点击计算按钮!');
        return;
    }
    formRef.value.validate((valid, fields) => {
        if (valid) {
            addInterest({
                loanRecordId:selectedArr.value[0].loanRecordId,
                startTime:interestForm.startTime,
                endTime:interestForm.endTime,
                calculateAmount:selectedArr.value[0].loanAmount,
                interestAmount:amountMoney.value,
            },(res)=>{
                setTimeout(()=>{
                    ElMessage.success('操作成功!');
                },1500);
                visible.value = false;
                publicTableRef.value.clearSelection();
                selectedArr.value = [];
                page.current = 1;
                page.size = 10;
                getData({
                    pageNum:1,
                    pageSize:10
                });
            },()=>{
                ElMessage.error('操作失败,请联系管理员!');
                visible.value = false;
                publicTableRef.value.clearSelection();
                selectedArr.value = [];
                page.current = 1;
                page.size = 10;
                getData({
                    pageNum:1,
                    pageSize:10
                });
            });
        } else {
            console.log('error submit!', fields)
        }
    });
}

/**
 * 计提时间被选择时触发
 *
 */
const onChange = (e) => {
    if(e===null || (e instanceof Array && e.length===0)){
        interestForm.startTime = '';
        interestForm.endTime = '';
        return;
    }
    interestForm.startTime = e[0];
    interestForm.endTime = e[1];
}

/**
 * 跳转还款详情
 * @param row
 */
const router = useRouter();
const toDetails = (row,type) => {
    if(type === '1'){
        return router.push({path:`/businessFinance/bankManagement/bankInformation/repaymentDetails/${row.loanRecordId}`});
    }
    if(type === '2'){
        // return router.push({path:`/businessFinance/bankManagement/bankInformation/summaryInterestCalculation`});
        return router.push({path:`/businessFinance/bankManagement/bankInformation/interestCalculationDetails`});
    }
}

/**
 * 发起还款
 */
const initiateRepaymentLoading = ref(false);
const initiateRepaymentHandle = () => {
    if(selectedArr.value.length===0){
        ElMessage.warning('请选择一条要操作的数据!');
        return;
    }
    initiateRepaymentLoading.value = true;
    bankManagementApi.addCompanyRepayment(selectedArr.value[0]).then(res=>{
        if(res.code === '200'){
            initiateRepaymentLoading.value = false;
            selectedArr.value = [];
            ElMessage.success('发起还款成功!');
            publicTableRef.value.clearSelection();
        }else{
            initiateRepaymentLoading.value = false;
            selectedArr.value = [];
            ElMessage.error('发起还款失败,请联系管理员!');
            publicTableRef.value.clearSelection();
        }
    });
}

/**
 * 查看明细
 */
const viewDetails = () => {
    router.push({path:'/businessFinance/bankManagement/bankInformation/interestCalculationDetails'})
}

onMounted(()=>{
    getData({
        pageNum:1,
        pageSize:10
    });
    getCompanyList();
});
</script>

<style lang="scss" scoped>
.internalTransactionRecordsPage{
  .search-wrap{
    .search-item{

      .el-input{
        width: auto !important;
      }
    }
    .search-buttons{
      .icon-export{
        width: 18px;
        height: 18px;
      }
    }
  }
}

.public-dialog-content{
  .dialog-title-box{
      height: 30px;
      span{
          font-size: 15px;
          font-weight: 600;
      }
  }
}
</style>
